package com.xyy.saas.payment.manager;

import cn.hutool.core.collection.CollUtil;
import com.xyy.saas.payment.common.model.Tuple2;
import com.xyy.saas.payment.dao.mapper.LoanRepayPlanDetailMapper;
import com.xyy.saas.payment.dao.mapper.LoanRepayPlanMapper;
import com.xyy.saas.payment.dao.mapper.OrderTransDataMapper;
import com.xyy.saas.payment.dao.model.LoanRepayPlanDetailPo;
import com.xyy.saas.payment.dao.model.LoanRepayPlanPo;
import com.xyy.saas.payment.dao.model.OrderTransDataPo;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liujf
 */
@Repository
public class PayManager {
    @Resource
    private OrderTransDataMapper orderTransDataMapper;


    @Resource
    private LoanRepayPlanMapper loanRepayPlanMapper;

    @Resource
    private LoanRepayPlanDetailMapper loanRepayPlanDetailMapper;


    @Transactional(rollbackFor = Exception.class)
    public void insertOrderTrans(OrderTransDataPo orderTransDataPo, LoanRepayPlanPo repayPlanPo, List<LoanRepayPlanDetailPo> repayPlanDetailPos) {
        orderTransDataMapper.insertSelective(orderTransDataPo);
        if (repayPlanPo != null) {
            loanRepayPlanMapper.insert(repayPlanPo);
        }

        if (CollUtil.isNotEmpty(repayPlanDetailPos)) {
            loanRepayPlanDetailMapper.batchInsert(repayPlanDetailPos);
        }
    }

    public OrderTransDataPo queryOrderTransData(String payNo) {
        return orderTransDataMapper.queryOrderTransByPayNo(payNo);
    }

    public void insertOrderTransData(OrderTransDataPo orderTransDataPo) {
        orderTransDataMapper.insertSelective(orderTransDataPo);
    }

    public Tuple2<LoanRepayPlanPo, List<LoanRepayPlanDetailPo>> queryRepayPlanAndDetails(String payNo) {
        LoanRepayPlanPo repayPlanPo = loanRepayPlanMapper.queryByPayNo(payNo);
        List<LoanRepayPlanDetailPo> planDetailPos = loanRepayPlanDetailMapper.queryByPayNo(payNo);
        return new Tuple2<>(repayPlanPo, planDetailPos);
    }

    public void updateRepayPlan(LoanRepayPlanPo updateRepayPlanPo, List<LoanRepayPlanDetailPo> updatePlanDetailList) {
        loanRepayPlanMapper.updateByPrimaryKeySelective(updateRepayPlanPo);

        if (CollUtil.isNotEmpty(updatePlanDetailList)) {
            loanRepayPlanDetailMapper.batchUpdateByIdSelective(updatePlanDetailList);
        }
    }
}
